Return to doc.sitecore.com

Valid for Sitecore 5.3.1
4.  Date and Datetime
Prev Next

Date and Datetime fields hold date and date & time respectively.

The best way of formatting dates in XSLT code is using the Date XSL Control.

<sc:date field="My Datetime"/>

The format attribute of the <sc:date/> tag allows you to specify the formatting.

The following code will output the year:

<sc:date field="My Datetime" format="yyyy"/>

The following code will output the month:

<sc:date field="My Datetime " format="MM"/> 

The same result can be achieved by using the DateUtil.FormatIsoDate function. To use the DateUtil class in an XSLT template you need to define the dateutil namespace in your stylesheet:

xmlns:dateutil=http://www.sitecore.net/dateutil

and add toin web.config in the section <xslExtensions>:

<extension mode="on" type="Sitecore.DateUtil, Sitecore.Kernel" namespace="http://www.sitecore.net/dateutil" singleInstance="true" />

Then the function can be used in the following way:

<xsl:value-of select="dateutil:FormatIsoDate(sc:fld('My Datetime',.))"/><br/>

<xsl:value-of select="dateutil:FormatIsoDate(sc:fld('My Datetime',.), 'yyyy')"/>

Corresponding output:

Thursday, January 17, 2008 12:00 PM
2008 

Important Note: The FormatIsoDate function maps directly to the corresponding .Net classes. For formatting characters please refer to this section at MSDN:
http://msdn.microsoft.com/library/ default.asp?url=/library/en-us/cpref/html/frlrfsystemglobalizationdatetimeformatinfoclasstopic.asp

The XSL example below will output the list of the datetime field values sorted by date. The list will be populated by the items of the same level in the content tree:

<xsl:for-each select="./../item">
  
<xsl:sort select="sc:fld('My Datetime',.)" order="descending"/>
  A nice date:
<xsl:value-of select="dateutil:FormatIsoDate(sc:fld('My Datetime',.))"/><br/>
</xsl:for-each>

Sample Content Editor input:

Corresponding output in the Preview mode:



Prev Next